package com.gitee.genshin.analyse.data.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.log.Log;
import com.gitee.genshin.analyse.Main;
import com.gitee.genshin.analyse.data.GenshinDataService;
import com.gitee.genshin.analyse.data.GenshinDataType;
import com.gitee.genshin.analyse.data.vo.GenshinData;

import java.util.List;

import static com.gitee.genshin.analyse.data.GenshinDataRequester.getApi;
import static com.gitee.genshin.analyse.data.GenshinDataRequester.getData;

/**
 * 数据同步服务
 *
 * @author hongda.li@dlmu.qq.com 2022/7/13 15:43
 */
public class SaveService extends GenshinDataService {
    private static final boolean SAVE = Main.CONFIG.getBool("data.save");
    @Override
    public void doService() {
        if (!SAVE){
            return;
        }
        for (GenshinDataType value : GenshinDataType.values()) {
            Log.get().info("开始同步[{}]祈愿类型数据", value.getName());
            List<GenshinData> data = getData(getApi(0, value));
            int temp = 1;
            while (!CollUtil.isEmpty(data)) {
                for (GenshinData genshinData : data) {
                    // 避免重复保存数据
                    if (exists(genshinData.getId())) {
                        continue;
                    }
                    CONNECTION.insert(genshinData);
                }
                data = getData(getApi(data.get(data.size() - 1).getId(), value));
                Log.get().info("等待数据同步[{}]s，同步数据量[{}]条", temp, 20 * temp);
                ThreadUtil.safeSleep(1000);
                temp++;
            }
            Log.get().info("[{}]祈愿类型数据同步完成", value.getName());
        }
    }
}
